package com.hlf.modules.merchant.goods.service.impl;

import com.hlf.common.constants.FileConstants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.IdWorkerFactory;
import com.hlf.common.utils.PageUtils;
import com.hlf.common.utils.Query;
import com.hlf.modules.api.interceptor.AuthorizationInterceptor;
import com.hlf.modules.merchant.goods.entity.Goods;
import com.hlf.modules.merchant.goods.entity.GoodsType;
import com.hlf.modules.merchant.goods.mapper.GoodsMapper;
import com.hlf.modules.merchant.goods.mapper.GoodsTypeMapper;
import com.hlf.modules.merchant.goods.service.GoodsService;
import com.hlf.modules.merchant.merchant.mapper.MerchantMapper;
import com.hlf.modules.merchant.store.entity.Store;
import com.hlf.modules.merchant.store.service.StoreService;
import com.hlf.modules.sys.entity.File;
import com.hlf.modules.sys.entity.SysUserEntity;
import com.hlf.modules.sys.mapper.FileMapper;
import com.hlf.modules.sys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private GoodsTypeMapper goodsTypeMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private StoreService storeService;
    @Autowired
    private FileMapper fileMapper;

    /**
     * 查询单个商品
     *
     * @param id
     * @return
     */
    @Override
    public Goods queryObject(Long id) {
        return goodsMapper.queryObject(id);
    }

    @Override
    public List<Goods> queryList(Map<String, Object> map) {
        return null;
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return 0;
    }

    /**
     * 保存
     *
     * @param goods
     */
    @Override
    public void save(Goods goods) {
        goodsMapper.save(goods);
    }

    /**
     * 选择性新增
     *
     * @param goods
     * @return
     */
    @Override
    public int insertSelective(Goods goods) {
        return goodsMapper.insertSelective(goods);
    }

    /**
     * 分页查询
     */
    @Override
    public PageUtils queryListForPage(Map<String, Object> map) {
        Query query = new Query(map);
        int total = goodsMapper.queryTotal(query);
        List<Goods> goodsList = null;
        if (total > 0) {
            goodsList = goodsMapper.queryList(query);
            for (Goods goods : goodsList) {
                Long goodsTypeId = goods.getGoodsType();
                GoodsType goodsType = goodsTypeMapper.queryObject(goodsTypeId);
                if (goodsType == null) {
                    continue;
                }
                goods.setGoodsTypeName(goodsType.getName());
            }
        }

        return new PageUtils(goodsList, total, query.getLimit(), query.getPage());
    }

    /**
     * 批量逻辑删除 商品
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateDel(Long[] goodsIds, Long userId) {
        List<Long> goodsIdList = Arrays.asList(goodsIds);
        for (Long aLong : goodsIdList) {
            fileMapper.deleteByForeignIdAndFilType(aLong, FileConstants.GOODS_IMG);
        }
        return goodsMapper.batchUpdateDel(goodsIdList, userId);
    }

    /**
     * 修改
     * @param goods
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(Goods goods) {
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    /**
     * 根据门店id查商品集合
     *
     * @param storeId
     * @return
     */
    @Override
    public List<Goods> queryListForStoreId(Long storeId) {
        return goodsMapper.queryListForStoreId(storeId);
    }

    /**
     * 查询本店茶位费
     *
     * @param storeId
     * @return
     */
    @Override
    public Goods queryTeaForStoreId(Long storeId) {
        return goodsMapper.queryTeaForStoreId(storeId);
    }

    /**
     * 创建
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SysUserEntity user, Goods goods) {
        Long userId = user.getUserId();
        long id = IdWorkerFactory.nextId();
        List<File> goodsImgs = goods.getGoodsImg();
        for (File goodsImg : goodsImgs) {
            goodsImg.setInsertBy(userId);
            goodsImg.setForeignId(id);
        }
        fileService.inserts(goodsImgs);
        String storeId = user.getCurrentStoreId();
        Store store = storeService.queryObject(Long.parseLong(storeId));
        Long merchantId = store.getMerchantId();

        goods.setId(id);
        goods.setMerchantId(merchantId);
        goods.setStoreId(Long.parseLong(user.getCurrentStoreId()));
        goods.setNum(IdWorkerFactory.nextId());
        goods.setRemainQty(goods.getInitQty());
        goods.setInsertBy(userId);
        insertSelective(goods);
    }

    /**
     * 修改
     */
    @Override
    @Transactional
    public void updateGoods(SysUserEntity user, Goods goods) {
        Long userId = user.getUserId();
        goods.setLastUpdateBy(userId);
        List<File> goodsImg = goods.getGoodsImg();
        for (File img : goodsImg) {
            img.setInsertBy(userId);
            img.setForeignId(goods.getId());
            File file = fileService.selectById(img.getFilId());
            if (file == null) {
                Long id = IdWorkerFactory.nextId();
                img.setFilId(id);
                fileMapper.insert(img);
            }
        }
        updateByPrimaryKeySelective(goods);
    }

    /**
     * 售罄/上下架/修改茶位费
     *
     * @param goodsId
     * @param status
     * @param request
     * @param teaPri
     */
    @Override
    public void updateGoodsStatus(String goodsId, String status, HttpServletRequest request, String teaPri) {
        Long userId = (Long) request.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY);
        Goods goods = new Goods();
        goods.setId(Long.parseLong(goodsId));
        goods.setLastUpdateBy(userId);

        if (status != null && status.length() > 0) {
            goods.setStatus(Byte.parseByte(status));
        } else if (teaPri != null && teaPri.length() > 0) {
            goods.setSellPrice(Integer.parseInt(teaPri));
        } else {
            throw new BusinessException("数据不能为空!");
        }

        int i = updateByPrimaryKeySelective(goods);
        if (i == 0) {
            throw new BusinessException("更改失败!");
        }
    }

    /**
     * 定时触发任务
     */
    @Override
    public void freshenStock() {
        List<Goods> goodsList = goodsMapper.dailyStockGoodsList();
        for (Goods goods : goodsList) {
            goods.setRemainQty(goods.getInitQty());
            goodsMapper.freshenStockUpdate(goods);
        }
    }

}
